<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>数组排序</title>
</head>
<body>
    
    <script>
        var ary = [10,15,12,36,27,73,46,54];

        // 冒泡排序法

        function bubbleSort(ary){

            for(var i=0;i< ary.length - 1;i++){
                for(var j=0;j<ary.length - 1 - i;j++){
                    if(ary[j]>ary[j+1]){
                        [ary[j],ary[j+1]] = [ary[j+1],ary[j]];
                    }
                }
            }
            return ary;
        }

        console.log(bubbleSort(ary));

        // 插入排序法

        function insertSort(ary){
            var aryNew = [];
            aryNew.push(ary[0]);           
            for(var i=1;i<ary.length;i++){
                var aryItem = ary[i];
                for(var j=aryNew.length-1;j>=0;j--){
                    var aryNewItem = aryNew[j];
                    if(aryItem>aryNewItem){
                        aryNew.splice(j+1,0,aryItem);
                        break;
                    }
                    if(j === 0){
                        aryNew.unshift(aryItem);
                    }
                }
            }

            return aryNew;
        }

        console.log(insertSort(ary));

        {
            // 快速排序


            let ary = [10,15,12,36,27,73,46,54];

            function rapidSort (ary) {

                if (ary.length <= 1) {
                    return ary;
                }

                let index = Math.floor(ary.length/2);
                let aryCenterEle = ary.splice(index,1)[0];
                let left = [],right = [];
                for(let i=0;i<ary.length;i++){
                    let ele = ary[i];
                    ele>aryCenterEle?right.push(ele):left.push(ele);
                }
                return rapidSort(left).concat(aryCenterEle,rapidSort(right));
            }

            console.log(rapidSort(ary));
        }


    
    </script>
</body>
</html>